package random.fox.p2p.ui;

import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.widget.EditText;
import android.widget.LinearLayout;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import random.fox.p2p.IndexActivity;
import random.fox.p2p.R;
import random.fox.p2p.event.FinishActivityEvent;
import random.fox.p2p.ui.customview.TagSpan;

/**
 * Created by wq on 15/3/14.
 */
public class RegisterFinishView extends LinearLayout {
    @InjectView(R.id.edt_set_tags)
    EditText edtTags;

    public RegisterFinishView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        ButterKnife.inject(this);
        edtTags.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String tmp = s.toString().replaceAll("，",",");
                if (tmp.lastIndexOf(',') == (tmp.length() - 1) && tmp.length() > 1) {
                    String string = edtTags.getText().toString().replaceAll("，",",");
                    String[] trims = string.split(",");
                    TagSpan[] spans = edtTags.getText().getSpans(0, string.length(), TagSpan.class);
                    if (trims.length == spans.length) {
                        return;
                    } else {
                        String last = trims[trims.length - 1];
                        int begin = string.length() - last.length() - 1; //-1 是','的位置
                        int end = string.length() - 1;//-1 是','的位置
                        TagSpan tagSpan = new TagSpan(getContext(), last);
                        edtTags.getText().setSpan(tagSpan, begin, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    @OnClick(R.id.btn_next)
    void nextClicked() {
        Intent intent = new Intent(getContext(), IndexActivity.class);
        getContext().startActivity(intent);
        EventBus.getDefault().post(new FinishActivityEvent());
    }
}
